package com.example.dmweb.policy;


import com.example.dmcommom.ResponseResult;
import com.example.dmdomain.PolicyRepository;
import com.example.dmdomain.entity.Policy;
import com.example.dmweb.policy.model.EnumPolicy;
import com.example.dmweb.policy.model.PolicyModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/policy")
@CrossOrigin
@Api(value = "官网-政策", tags = {"政策"})
public class PolicyController {

    @Resource
    PolicyRepository repository;

    @ApiOperation("查基本信息")
    @RequestMapping(value = "/getBaseInfo", method = {RequestMethod.POST})
    public ResponseResult getBaseInfo() {
        List<Policy> policyList = repository.findPoliciesByUseType(1);
        // 根据 company 和 district 进行分组，并计算数量
        List<Map<String, Object>> resultList = policyList.stream()
                .collect(Collectors.groupingBy(Policy::getCompany,
                        Collectors.collectingAndThen(Collectors.counting(), Long::intValue)))
                .entrySet().stream()
                .map(entry -> {
                    Map<String, Object> companyMap = new HashMap<>();
                    companyMap.put("company", entry.getKey());
                    companyMap.put("areaList", EnumPolicy.Area.getValues(entry.getKey()));
                    List<Map<String, Object>> areaList = policyList.stream()
                            .filter(policy -> policy.getCompany().equals(entry.getKey()))
                            .collect(Collectors.groupingBy(Policy::getDistrict, Collectors.counting()))
                            .entrySet().stream()
                            .map(e -> {
                                Map<String, Object> areaMap = new HashMap<>();
                                areaMap.put("name", e.getKey());
                                areaMap.put("num", e.getValue());
                                return areaMap;
                            })
                            .collect(Collectors.toList());
                    companyMap.put("area", areaList);
                    companyMap.put("publishNum", entry.getValue());

                    return companyMap;
                })
                .collect(Collectors.toList());
        int published = policyList.stream().collect(Collectors.groupingBy((Policy::getDistrict))).size();
        Map<String,Object> map = new HashMap<>();
        map.put("list",resultList);
        map.put("published",published);
        map.put("unpublished",100 - published);

        return ResponseResult.success(map);
    }
    @ApiOperation("查文件详情")
    @RequestMapping(value = "/getFileInfo", method = {RequestMethod.POST})
    public ResponseResult getFileInfo(@RequestBody PolicyModel model) {
        try {
            Policy policy = repository.findPolicyByCompanyAndDistrictAndUseType(model.getCompany(),
                    model.getDistrict(), model.getUseType());
            if (policy == null) {
                return ResponseResult.error("无文件");
            }
            File file = new File("/data/guanwanglinshi/test.pdf");
            PDDocument document = PDDocument.load(file);
            PDFTextStripper pdfTextStripper = new PDFTextStripper();
            String content = pdfTextStripper.getText(document);
            Map<String,Object> map = new HashMap<>();
            map.put("publishUnit", policy.getPublishUnit());
            map.put("policyName", policy.getPolicyName());
            map.put("content", content);
            map.put("updateTime", policy.getUpdateTime());
            document.close();
            return ResponseResult.success(map);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.error("无文件");
        }

    }
    @ApiOperation("查文件列表")
    @RequestMapping(value = "/getFileList", method = {RequestMethod.POST})
    public ResponseResult getFileList(@RequestBody PolicyModel model) {

        return ResponseResult.success(repository.findPoliciesByDistrict(model.getDistrict()).stream()
                .map(policy -> {
                    Map<String, Object> policyData = new HashMap<>();
                    policyData.put("id", policy.getId());
                    policyData.put("documentName", policy.getDocumentName());
                    policyData.put("policyName", policy.getPolicyName());
                    policyData.put("publishTime", policy.getPublishTime());
                    return policyData;
                })
                .collect(Collectors.toList()));
    }

    @ApiOperation("下载文件")
    @RequestMapping(value = "/downFile", method = {RequestMethod.POST})
    public ResponseEntity downFile(@RequestBody PolicyModel model) {
        try {
            Policy policy = repository.findById(model.getId()).orElse(null);
            if (policy == null) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件不存在");
            }
            File file = new File("/data/guanwanglinshi/test.pdf");
            InputStream inputStream = Files.newInputStream(file.toPath());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String encodedFileName = URLEncoder.encode(policy.getDocumentName(), "UTF-8");
            headers.setContentDispositionFormData("attachment", encodedFileName);

            return new ResponseEntity<>(new InputStreamResource(inputStream), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("不存在");
        }
    }
}
